﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace EpiMapit
{
    public static class Extensions
    {
        public static string ToKml(this Color color)
        {
            StringBuilder sb = new StringBuilder();
            ToHex(color.A, sb);
			ToHex(color.B, sb);
			ToHex(color.G, sb);
			ToHex(color.R, sb);
			return sb.ToString();
        }

        public static BoundingBox GetBoundingBox(this IEnumerable<IKmlFigure> figures)
        {
            return new BoundingBox(figures);
        }

        public static Dictionary<T, U> Clone<T, U>(this Dictionary<T, U> dictionary)
        {
            var clone = new Dictionary<T, U>();
            dictionary.ForEach(e => clone.Add(e.Key, e.Value));
            return clone;
        }

        public static HashSet<T> Clone<T>(this HashSet<T> hashSet)
        {
            var clone = new HashSet<T>();
            clone.AddRange(hashSet);
            return clone;
        }

        public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> values)
        {
            values.ForEach(x => collection.Add(x));
        }

        public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
        {
            foreach (var value in values)
            {
                action(value);
            }
        }

        private static void ToHex(int value, StringBuilder sb)
        {
            ToSingleHex(value / 16, sb);
            ToSingleHex(value % 16, sb);
        }

        private static void ToSingleHex(int value, StringBuilder sb)
        {
            if (value < 0 || value > 15)
                throw new ArgumentException("Value must be between 0 and 15");

            if (value < 10)
                sb.Append(value);
            else
                sb.Append((char)('A' + (value - 10)));
        }
    }
}
